package com.refusea.train.config.mvc

import com.refusea.train.domain.cache.TokenCache
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.http.HttpMethod
import org.springframework.stereotype.Component
import org.springframework.web.servlet.HandlerInterceptor

@Component
class AuthorizationInterceptor(private val tokenCache: TokenCache) : HandlerInterceptor {

    private val options = HttpMethod.OPTIONS.name()

    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {

        if (options == request.method) {
            return true
        }

        if (request.requestURI.startsWith("/api/private")) {

            val token = request.getHeader("Authorization")?.substringAfter("Bearer ")

            if (token.isNullOrEmpty()) {
                response.status = HttpServletResponse.SC_UNAUTHORIZED
                return false
            }

            val user = tokenCache.get(token)

            if (user == null) {
                response.status = HttpServletResponse.SC_UNAUTHORIZED
                return false
            }

            WebSession.hold(token, user)
        }

        return true
    }
}

